package org.yinweichen.llm_dataset_backend.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.yinweichen.llm_dataset_backend.DTO.OriginalQuestionCreateDTO;
import org.yinweichen.llm_dataset_backend.entity.OriginalQuestion;
import org.yinweichen.llm_dataset_backend.entity.OriginalQuestionId;
import org.yinweichen.llm_dataset_backend.repository.OriginalQuestionRepository;
import org.yinweichen.llm_dataset_backend.service.OriginalQuestionService;
import org.yinweichen.llm_dataset_backend.util.IdGenerator;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@Service
@RequiredArgsConstructor
public class OriginalQuestionServiceImpl implements OriginalQuestionService {
    private final OriginalQuestionRepository repository;
    private final IdGenerator idGenerator;

    // 新增OriginalQuestion
    public ResponseEntity<OriginalQuestion> createQuestion(String version,OriginalQuestionCreateDTO request) {
        try {
            // 参数验证
            if (request == null) {
                return ResponseEntity.badRequest().build();
            }
            if (version == null || version.isEmpty() ||
                request.title() == null || request.title().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }

            Date now = new Date();
            OriginalQuestion question = OriginalQuestion.builder()
                .id(idGenerator.generateUniqueIdForOriginalQuestion())
                .version(version)
                .title(request.title())
                .updateTime(now)
                .content(request.content())
                .source(request.source())
                .active(true)
                .build();

            OriginalQuestion savedQuestion = repository.save(question);
            return ResponseEntity.status(HttpStatus.CREATED).body(savedQuestion);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    // 更新OriginalQuestion
    public void updateQuestion(Long id, String version,OriginalQuestionCreateDTO request) {
        Date now = new Date(); // 获取当前时间
        repository.findById(new OriginalQuestionId(id, version))
            .map(existing -> {
                existing.setTitle(request.title());
                existing.setUpdateTime(now);
                existing.setContent(request.content());
                existing.setSource(request.source());
                return repository.save(existing);
            })
            .orElseThrow(() -> new RuntimeException("Question not found"));
    }
    //根据title模糊查询OriginalQuestion
    public List<OriginalQuestion> searchForQuestions(String title, String version) {
        if (version != null) {
            return repository.findByTitleLikeAndVersion(title, version);
        } else {
            return repository.findByTitleLike(title);
        }
    }
    //统一查询OriginalQuestion
    public List<OriginalQuestion> getQuestions(Long id, String version) {
        if (version != null) {
            List<OriginalQuestion> result = new ArrayList<>();
            repository.findByIdAndVersion(id, version)
                .ifPresent(result::add);
            if (result.isEmpty()) {
                throw new RuntimeException("Question not found");
            }
            return result;
        } else {
            return repository.findAllById(id);
        }
    }

    //硬删除
    public void deleteQuestions(Long id, String version) {
        if (version != null) {
            // 删除指定版本的中所有被标记为inactive的问题
            repository.hardDelete(version);
        }
    }
    // 禁用OriginalQuestion(软删除)
    public void inactivateQuestion(Long id, String version) {
        repository.inactivate(id, version);
    }
    //启用OriginalQuestion


    @Override
    public void activateQuestion(Long id, String version) {
        repository.activate(id,version);
    }

    @Override
    public List<OriginalQuestion> findAllQuestions(String version, int page, int size) {
        return repository.findAllByVersion(version, PageRequest.of(page, size));
    }

    @Override
    public long countSearchResults(String title, String version) {
        if (title != null) {
            return repository.countByTitleLikeAndVersion(title, version);
        } else {
            return repository.countByVersion(title);
        }
    }
}
